package com.library.web.controller.api;

import com.alibaba.fastjson.JSON;
import com.library.api.service.IHomeApiService;
import com.library.common.core.controller.BaseController;
import com.library.common.core.domain.AjaxResult;
import com.library.common.utils.StringUtils;
import com.library.domain.HotConfig;
import com.library.enums.HotTypeEnum;
import com.library.picture.books.entity.PictureBooksInfo;
import com.library.picture.books.service.IPictureBooksInfoService;
import com.library.service.IHotConfigService;
import com.library.vo.HomeModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @Author julyWhj
 * @Description 首页接口 $
 * @Date 2022/3/28 10:50 上午
 **/
@RestController
@RequestMapping("/api/home")
public class HomeApiController extends BaseController {
    @Autowired
    private IHomeApiService homeApiService;

    @Autowired
    private IHotConfigService hotConfigService;
    @Autowired
    private IPictureBooksInfoService pictureBooksInfoService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String HOME_KEY = "app:home:";

    @GetMapping
    public AjaxResult home() {
        String s = redisTemplate.opsForValue().get(HOME_KEY);
        if (StringUtils.isNotEmpty(s)) {
            return AjaxResult.success(JSON.parseObject(s, HomeModel.class));
        }
        HomeModel home = homeApiService.home();
        HotConfig config = new HotConfig();
        config.setHotType(HotTypeEnum.PICTURE.getType());
        List<HotConfig> hotConfigs = hotConfigService.selectHotConfigList(config);
        List<PictureBooksInfo> pictureBooksInfos = new ArrayList<>();
        hotConfigs.forEach(hotConfig -> {
            PictureBooksInfo pictureBooksInfo = pictureBooksInfoService.selectPictureBooksInfoByNo(hotConfig.getHotId());
            pictureBooksInfos.add(pictureBooksInfo);
        });
        home.setPictureBooksInfos(pictureBooksInfos);
        redisTemplate.opsForValue().set(HOME_KEY, JSON.toJSONString(home));
        return AjaxResult.success(home);
    }

    @GetMapping("/test")
    public AjaxResult jenkinsTest() {
        return AjaxResult.success("jenkins test");
    }
}
